/* 
 *  <copyright file="FarseerPhysicsService.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;
using FarseerPhysics;
using FarseerPhysics.DebugViews;
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using SobrietyEngine.Events;
using SobrietyEngine.Events.Physics;

namespace SobrietyEngine.Physics
{
    public class FarseerPhysicsService:DrawableGameComponent, IPhysicsGameService, IEventListener
    {
        Dictionary<String,World> worlds = new Dictionary<String, World>();
        public Dictionary<String, World> Worlds { get { return worlds; } }

        Dictionary<String, DebugViewXNA> debugViews = new Dictionary<string, DebugViewXNA>();
        public Boolean CreateDebugViews { get; set; }

        IEventRouter EventRouter;

        //for physic world units and scaling
        public ConvertUnits ConvertUnits { get; set; }
       
        public FarseerPhysicsService(Game game)
            : base(game)
        {
            ConvertUnits = new ConvertUnits();
            ConvertUnits.SetDisplayUnitToSimUnitRatio(100);
            Game.Services.AddService(typeof(IPhysicsGameService), this);
        }

        public override void Initialize()
        {
            base.Initialize();
            
            EventRouter = (IEventRouter)Game.Services.GetService(typeof(IEventRouter));
            RegisterEventListeners();
        }

        public virtual void RegisterEventListeners()
        {
            EventRouter.AddEventListener(typeof(TogglePhysicsDebug), this);
        }

        public virtual void UnregisterEventListeners()
        {
            EventRouter.RemoveEventListener(this);
        }

        public void HandleEvent(Event e)
        {
            if (e.Type == typeof(TogglePhysicsDebug))
            {
                TogglePhysicsDebug tpd = (TogglePhysicsDebug)e.Data;
                //i know, in order to test ill toggle all of em.
                //since we cant yet send in the correct physics world name
                foreach(DebugViewXNA dv in debugViews.Values)
                    dv.Enabled = !dv.Enabled;
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            UnregisterEventListeners();
        }

        public void AddDebugView(String worldName, Boolean debug)
        {
            if (debug == false)
            {
                //rmove debug view
                return;
            }

            if (debugViews.ContainsKey(worldName))
            {
                Logging.Logger.GetSingleton().WriteError("FarserPhysics::AddDebugView(): with name " + worldName + " already exists");
                return;
            }
            
            debugViews[worldName] = new DebugViewXNA(Worlds[worldName]);
            debugViews[worldName].AppendFlags(DebugViewFlags.Joint);// | DebugViewFlags.DebugPanel);
            //debugViews[worldName].AppendFlags(DebugViewFlags.ContactPoints |  DebugViewFlags.PolygonPoints);
            debugViews[worldName].AppendFlags(DebugViewFlags.Shape | DebugViewFlags.ContactNormals);
            debugViews[worldName].DefaultShapeColor = Color.White;
            debugViews[worldName].SleepingShapeColor = Color.DarkBlue;
            debugViews[worldName].KinematicShapeColor = Color.Red;
            debugViews[worldName].LoadContent(this.Game.GraphicsDevice, this.Game.Content);
        }

        public void AddWorld(String worldName, Vector2 gravity)
        {
            if (Worlds.ContainsKey(worldName))
                Logging.Logger.GetSingleton().WriteError("FarserPhysics::AddWorld(): with name " + worldName + " already exists");
            else
                Worlds[worldName] = new World(gravity);

            AddDebugView(worldName, CreateDebugViews);
        }

        public void AddWorld(String worldName)
        {
            AddWorld(worldName, Vector2.Zero);
        }

        public void RemoveWorld(String worldName)
        {
            if (!Worlds.ContainsKey(worldName))
                Logging.Logger.GetSingleton().WriteError("FarserPhysics::RemoveWorld(): with name " + worldName + " doesn't exist");
            else
                Worlds[worldName].Clear();
                
            Worlds.Remove(worldName);

            if (debugViews.ContainsKey(worldName))
            {
                debugViews[worldName].Enabled = false;
                debugViews.Remove(worldName);
            }
            
        }

        protected override void LoadContent()
        {
            base.LoadContent();
        }

        float updateSlice = 0.0f;
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);            
            updateSlice = (gameTime.ElapsedGameTime.Milliseconds * .001f);// / 2.0f;

            foreach (World w in Worlds.Values)
            {
                //for (int ups = 0; ups < 2; ++ups)
                w.Step(updateSlice);
            }
            
        }

        protected override void UnloadContent()
        {
            base.UnloadContent();
            foreach (String worldName in Worlds.Keys)
            {
                RemoveWorld(worldName);
            }
        }

        public void Draw(String worldName, Microsoft.Xna.Framework.GameTime gameTime, Matrix transformation, Matrix view)
        {
            if(debugViews.ContainsKey(worldName))
                debugViews[worldName].RenderDebugData(ref transformation, ref view);

            base.Draw(gameTime); 
        }
        /*
        public void Draw(Microsoft.Xna.Framework.GameTime gameTime, Matrix transformation, Matrix view)
        {
            foreach (DebugViewXNA dv in debugViews.Values)
            {
                dv.RenderDebugData(ref transformation, ref view);
            }
            base.Draw(gameTime);            
        }*/

    }
}